package kr.co.cherryt.activity;

import kr.co.cherryt.cherryt.R;
import kr.co.cherryt.common.CC_Log;
import kr.co.cherryt.common.CherrytData;
import kr.co.cherryt.common.ImageCacheManager;
import kr.co.cherryt.common.Utility;
import kr.co.cherryt.parser.xml.XmlItem;
import kr.co.cherryt.parser.xml.XmlManager;
import kr.co.cherryt.parser.xml.XmlManager.XmlResponse;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

public class DetailPopupActivity extends Activity {
	
	final int CALLER_MOVIE = 1;

	private Button btnClose = null;
	private Button btnAddView = null;
	private Button btnInstallConfirm = null;
	
	private XmlManager xmlManager = null;
	
	private String m_szLinkUrl = null;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    
	    ImageCacheManager m_cacheManager = ImageCacheManager.getInstance(this);
	    
	    Intent intent = getIntent();
	    final String szNum = intent.getStringExtra("num");
		String szImageUrl = intent.getStringExtra("img_url");
		final String szTitle = intent.getStringExtra("title");
		String szContent = intent.getStringExtra("content");
		final String szCompanyName = intent.getStringExtra("company_name");
		String szPoint = intent.getStringExtra("point");
		m_szLinkUrl = intent.getStringExtra("link_url");
		final String szMovieUrl = intent.getStringExtra("movie_url");
		String szPointSaveType = intent.getStringExtra("point_save_type");
		final String szPackageName = intent.getStringExtra("package_name");
		
		// 전체 레이아웃 (투명)
		LinearLayout layoutMain = new LinearLayout(this);
		layoutMain.setOrientation(LinearLayout.VERTICAL);
		layoutMain.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
		layoutMain.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL);
	    
		// 팝업 부분 레이아웃
		LinearLayout ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.VERTICAL);
		ll.setPadding(Utility.DPFromPixel(DetailPopupActivity.this, 10), Utility.DPFromPixel(DetailPopupActivity.this, 10), Utility.DPFromPixel(DetailPopupActivity.this, 10), Utility.DPFromPixel(DetailPopupActivity.this, 10));
		ll.setBackgroundResource(R.drawable.popupboxbg);
		//ll.setBackgroundColor(Color.WHITE);
		LayoutParams param = new LinearLayout.LayoutParams(Utility.DPFromPixel(DetailPopupActivity.this, 410), LayoutParams.WRAP_CONTENT);
		//param.setMargins(Utility.DPFromPixel(DetailPopupActivity.this, 30), 0, Utility.DPFromPixel(DetailPopupActivity.this, 30), 0);
		ll.setLayoutParams(param);
		
		// X 버튼 레이아웃
		LinearLayout layoutTop = new LinearLayout(this);
		layoutTop.setGravity(Gravity.RIGHT);
		
		// X 버튼
		btnClose = new Button(this);
		btnClose.setLayoutParams(new LinearLayout.LayoutParams(Utility.DPFromPixel(DetailPopupActivity.this, 41), Utility.DPFromPixel(DetailPopupActivity.this, 37)));
		btnClose.setBackgroundResource(R.drawable.xbutton_normal);
		btnClose.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				btnClose.setBackgroundResource(R.drawable.xbutton_select);
				finish();
			}
		});
		
		layoutTop.addView(btnClose);
		ll.addView(layoutTop);
		
		// Body 레이아웃
		LinearLayout layoutBody = new LinearLayout(this); 
		layoutBody.setGravity(Gravity.CENTER_HORIZONTAL);
		layoutBody.setOrientation(LinearLayout.VERTICAL);
		layoutBody.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
		layoutBody.setPadding(Utility.DPFromPixel(DetailPopupActivity.this, 35), Utility.DPFromPixel(DetailPopupActivity.this, 5), Utility.DPFromPixel(DetailPopupActivity.this, 35), Utility.DPFromPixel(DetailPopupActivity.this, 10));
		//layoutBody.setBackgroundColor(Color.YELLOW);
		ll.addView(layoutBody);
		
		ImageView imgImage = new ImageView(this);
		imgImage.setLayoutParams(new LinearLayout.LayoutParams(Utility.DPFromPixel(DetailPopupActivity.this, 350), Utility.DPFromPixel(DetailPopupActivity.this, 200)));
		imgImage.setImageResource(R.drawable.imgbox);
		if(imgImage != null && Utility.IsEmpty(szImageUrl) == false && m_cacheManager != null){
			m_cacheManager.attachThumbailImage(szImageUrl, imgImage);
		}
		layoutBody.addView(imgImage);
		
		// point 레이아웃
		LinearLayout layoutPoint = new LinearLayout(this);
		layoutPoint.setOrientation(LinearLayout.HORIZONTAL);
		layoutPoint.setGravity(Gravity.CENTER_VERTICAL);
		layoutPoint.setPadding(0, 10, 0, 0);
		layoutBody.addView(layoutPoint);
		
		// + 아이콘
		ImageView imgPlusIcon = new ImageView(this);
		imgPlusIcon.setImageResource(R.drawable.popup_icon_poing);
		imgPlusIcon.setLayoutParams(new LinearLayout.LayoutParams(Utility.DPFromPixel(DetailPopupActivity.this, 25), Utility.DPFromPixel(DetailPopupActivity.this, 25)));
		
		// point 텍스트
		TextView tvPoint = new TextView(this);
		tvPoint.setTextColor(Color.parseColor("#45897D"));
		tvPoint.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13.5f);
		tvPoint.setText(szPoint);
		tvPoint.setPadding(5, 0, 0, 0);
		
		layoutPoint.addView(imgPlusIcon);
		layoutPoint.addView(tvPoint);
		
		// title 텍스트
		TextView tvTitle = new TextView(this);
		tvTitle.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16.0f);
		tvTitle.setPadding(0, 10, 0, 0);
		tvTitle.setText(szTitle);
		layoutBody.addView(tvTitle);
		
		// content 텍스트
		TextView tvContent = new TextView(this);
		tvContent.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12.5f);
		tvContent.setPadding(0, 10, 0, 20);
		tvContent.setText(szContent);
		layoutBody.addView(tvContent);
		
		// 버튼 레이아웃
		LinearLayout layoutButton = new LinearLayout(this);
		layoutButton.setOrientation(LinearLayout.HORIZONTAL);
		layoutButton.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.BOTTOM);
		layoutButton.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
		//layoutButton.setBackgroundColor(Color.GREEN);
		layoutBody.addView(layoutButton);
		
		// 광고 보기 버튼
		btnAddView = new Button(this);
		btnAddView.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, Utility.DPFromPixel(DetailPopupActivity.this, 65)));
		btnAddView.setBackgroundResource(R.drawable.btn01_normal);
		btnAddView.setTextColor(Color.WHITE);
		btnAddView.setText("광고 보기");
		btnAddView.setGravity(Gravity.CENTER_VERTICAL|Gravity.CENTER_HORIZONTAL);
		btnAddView.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				btnAddView.setBackgroundResource(R.drawable.btn01_select);
				
				XmlManager xmlManager = new XmlManager();
				
				String szUrl = CherrytData.getXmlUrl(DetailPopupActivity.this, "ct_click_log.php", "ad_num=" + szNum);
				CC_Log.info("jin", "조회수 로그 : " + szUrl);
		        xmlManager.fillItemArrayAsync(szUrl, null);
				
				// 광고 동영상 링크가 있으면 동영상 플레이어 실행
				if (!Utility.IsEmpty(szMovieUrl)) {
					Intent intentPlayer = new Intent(DetailPopupActivity.this, AdPlayerActivity.class);
					intentPlayer.putExtra("url", szMovieUrl);
					intentPlayer.putExtra("control", "no");
					intentPlayer.putExtra("title", szTitle);
					intentPlayer.putExtra("company", "");
					intentPlayer.putExtra("writer", szCompanyName);
	
					startActivityForResult(intentPlayer, CALLER_MOVIE);
				}
				// 동영상 링크가 없으면 종료 후 CherryTActivity 로 이동
				else {
					Intent intent = new Intent(DetailPopupActivity.this, CherryTActivity.class);
					intent.putExtra("szLinkUrl", m_szLinkUrl);
					setResult(1, intent);
					finish();
				}
			}
		});
		layoutButton.addView(btnAddView);
		
		// 설치 확인 버튼
		if (!Utility.IsEmpty(szPointSaveType) && (szPointSaveType.equals("A"))) {
			btnAddView.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, Utility.DPFromPixel(DetailPopupActivity.this, 65)));
			
			btnInstallConfirm = new Button(this);
			LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, Utility.DPFromPixel(DetailPopupActivity.this, 65));
			lp.setMargins(20, 0, 0, 0);
			btnInstallConfirm.setLayoutParams(lp);
			btnInstallConfirm.setBackgroundResource(R.drawable.btn01_normal);
			btnInstallConfirm.setTextColor(Color.WHITE);
			btnInstallConfirm.setText("적립 확인");
			btnInstallConfirm.setGravity(Gravity.CENTER_VERTICAL|Gravity.CENTER_HORIZONTAL);
			btnInstallConfirm.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					btnInstallConfirm.setBackgroundResource(R.drawable.btn01_select);
					
					PackageManager pm = getPackageManager();
					String szUserId = CherrytData.getUserId(DetailPopupActivity.this);
					
					if (!Utility.IsEmpty(szPackageName)) {
						//CC_Log.info("jin", "패키지네임 : " + szPName);
						boolean bInstall = Utility.installAppCheck(pm, szPackageName);
	            	
						// 앱이 설치된 경우
						if (bInstall) {
							String szUrl = CherrytData.getBaseUrl(DetailPopupActivity.this, "app_rss/app_install2.php", "userId=" + szUserId + "&pptitle=");
							CC_Log.info("jin", "앱 설치 포인트 적립 : " + szUrl);
							xmlManager = new XmlManager();
							xmlManager.setNewElementItemList("item_list", "item");
							xmlManager.fillItemArrayAsync(szUrl, m_hXmlManager, DetailPopupActivity.this, "잠시만 기다려 주세요.");
						}
						else {
							Utility.showAlert(DetailPopupActivity.this, "광고 시청 후 앱을 다운 받으면 포인트가 적립됩니다.");
							
							btnInstallConfirm.setBackgroundResource(R.drawable.btn01_normal);
						}
					}
				}
			});
			layoutButton.addView(btnInstallConfirm);
		}
		
		
		layoutMain.addView(ll);
		setContentView(layoutMain);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		
		super.onActivityResult(requestCode, resultCode, data);

		// 동영상 재생 완료 OR 중단 후 CherryTActivity 로 이동
		if (requestCode == CALLER_MOVIE) {
			
			Intent intent = new Intent(DetailPopupActivity.this, CherryTActivity.class);
			intent.putExtra("szLinkUrl", m_szLinkUrl);
			setResult(resultCode, intent);
			finish();
		}
	}
	
	// 앱 설치 포인트 적립 호출 완료시 실행
	Handler m_hXmlManager = new Handler() {
		public void handleMessage(Message msg) {
			XmlResponse rep = new XmlResponse(msg);
			if(rep.getXmlManager() == xmlManager){
			
				XmlItem item = xmlManager.getXmlItemList();
				//String szResultCode = item.getXmlElementData("resultCode");
				String szResultMsg = item.getXmlElementData("resultMsg");
				//String szMemberSrl = item.getXmlElementData("member_srl");
				
				if (szResultMsg != null) {
					Utility.showAlert(DetailPopupActivity.this, szResultMsg);
				}
				
				btnInstallConfirm.setBackgroundResource(R.drawable.btn01_normal);
			}
		}
	};
}
